package com.njcc.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DBCon {

	static Properties p = getProperties();
	public static String file_Path = p.getProperty("file_path");//文件的存储位置
	private static String mysql_url = p.getProperty("mysql_url");//数据库地址
	private static String databaseName = p.getProperty("mysql_database");//数据库名称
	private static String user = p.getProperty("mysql_user");//数据库的用户名
	private static String password = p.getProperty("mysql_password");//数据库的密码
	
	/**
	 * 封装MySQL数据库的方法
	 * @return connection对象
	 */
	public static Connection getCon(){
		Connection con = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			String url = "jdbc:mysql://"+mysql_url+databaseName ;
			con = DriverManager.getConnection(url, user, password);
		} catch (Exception e) {
			System.out.println(e);
		}
		return con;
	}
	
	/**
	 * 关闭与数据库的连接
	 * @param rs	 结果集
	 * @param st	状态集
	 * @param con	连接
	 */
	public static void closeAll(ResultSet rs, Statement st, Connection con){
		if(rs != null){
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			rs = null;
		}
		if(st != null){
			try {
				st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			st = null;
		}
		if(con!= null){
			try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			con = null;
		}
	}
	
	/**
	 * 获取config.properties文件
	 * @return properties对象
	 */
	public static Properties getProperties(){
		Properties p=null;
		p= new Properties();
		InputStream in =  DBCon.class.getResourceAsStream("/config.properties");
		try {
			p.load(in);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return p;
	}
		
}
